package com.ruoyi.util;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Collections;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SalaryHelper {
    /**
     * 简单实现{}模板功能
     * 如{aa} cc {bb} 其中 {aa}, {bb} 为占位符. 可用相关变量进行替换
     * @param templateStr 模板字符串
     * @param data     替换的变量值
     * @param defaultNullReplaceVals  默认null值替换字符, 如果不提供, 则为字符串""
     * @return 返回替换后的字符串, 如果模板字符串为null, 则返回null
     */

    @SuppressWarnings("unchecked")
    public static String simpleTemplate(String templateStr, Map<String, ?> data, String... defaultNullReplaceVals) {
        if(templateStr == null) return null;

        if(data == null) data = Collections.EMPTY_MAP;

        String nullReplaceVal = defaultNullReplaceVals.length > 0 ? defaultNullReplaceVals[0] : "";
        Pattern pattern = Pattern.compile("\\{([^}]+)}");

        StringBuffer newValue = new StringBuffer(templateStr.length());

        Matcher matcher = pattern.matcher(templateStr);

        while (matcher.find()) {
            String key = matcher.group(1);
            String r = data.get(key) != null ? data.get(key).toString() : nullReplaceVal;
            matcher.appendReplacement(newValue, r.replaceAll("\\\\", "\\\\\\\\")); //这个是为了替换windows下的文件目录在java里用\\表示
        }

        matcher.appendTail(newValue);

        return newValue.toString();
    }

    public static double evaluateFormula(String expression) {
        // 创建 ScriptEngine 对象
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");

        String fun = "function IF(a, b, c) {return a ? b : c}";
        expression = fun + "\n" + expression;

        try {
            // 执行 JavaScript 表达式
            Object output = engine.eval(expression);

            // 将结果转换为 double
            if (output instanceof Double) {
                return (Double) output;
            } else if (output instanceof Integer) {
                return ((Integer) output).doubleValue();
            } else {
                throw new IllegalArgumentException("无法解析结果为 double 类型");
            }
        } catch (ScriptException e) {
            e.printStackTrace();
            return Double.NaN; // 如果发生异常，返回 NaN
        }
    }
}
